/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {
  useCallback,
  useRef,
  forwardRef,
  useImperativeHandle,
} from 'react';
import type {
  MovingPhotoComponentType,
  NativeCommands,
} from './fabric/MovingPhotoNativeComponent';
import RNMovingPhotoComponent, {
  Commands,
} from './fabric/MovingPhotoNativeComponent';
import type {ReactMovingPhotoProps} from './types/photo';

export interface MovingPhotoViewRef extends NativeCommands {
  startPlayback: () => void;
  stopPlayback: () => void;
  refreshMovingPhoto: () => void;
}

const MovingPhotoView = forwardRef<MovingPhotoViewRef, ReactMovingPhotoProps>(
  (
    {
      source,
      isAutoPlay,
      isMuted,
      isRepeatPlay,
      autoPlayPeriod,
      style,
      resizeMode,
      enableAnalyzer,
      onComplete,
      onStart,
      onPause,
      onFinish,
      onError,
      onStop,
      ...rest
    },
    ref,
  ) => {
    const movingPhotoRef =
      useRef<React.ElementRef<MovingPhotoComponentType>>(null);

    const startPlayback = useCallback(() => {
      if (!movingPhotoRef.current) {
        return;
      }
      Commands.startPlayback(movingPhotoRef.current);
    }, []);
    const stopPlayback = useCallback(() => {
      if (!movingPhotoRef.current) {
        return;
      }
      Commands.stopPlayback(movingPhotoRef.current);
    }, []);
    const refreshMovingPhoto = useCallback(() => {
      if (!movingPhotoRef.current) {
        return;
      }
      Commands.refreshMovingPhoto(movingPhotoRef.current);
    }, []);
    useImperativeHandle(
      ref,
      () => ({
        startPlayback,
        stopPlayback,
        refreshMovingPhoto,
      }),
      [startPlayback, stopPlayback, refreshMovingPhoto],
    );

    return (
      <RNMovingPhotoComponent
        style={style}
        source={source}
        isAutoPlay={isAutoPlay}
        isMuted={isMuted}
        isRepeatPlay={isRepeatPlay}
        enableAnalyzer={enableAnalyzer}
        startTime={autoPlayPeriod?.startTime}
        endTime={autoPlayPeriod?.endTime}
        ref={movingPhotoRef}
        resizeMode={resizeMode}
        onComplete={onComplete}
        onStart={onStart}
        onPause={onPause}
        onFinish={onFinish}
        onError={onError}
        onStop={onStop}
        {...rest}
      />
    );
  },
);
export default MovingPhotoView;
